package cn.itsource.pet.service.impl;

import cn.itsource.basic.basic.BusinessException;
import cn.itsource.basic.service.IBaiduAiAuditService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.*;
import cn.itsource.order.domain.OrderPetAcquisition;
import cn.itsource.order.mapper.OrderPetAcquisitionMapper;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //id 自增长
        //title - 页面
        //state - 默认为0，审核之后修改
        //name - 页面
        //age - 页面
        //gender - 页面
        //coat_color - 页面
        //resources - 页面
        //pet_type - 页面
        //price - 页面
        //address - 页面
        //user_id - 来自登录人信息
        //shop_id - 百度地图根据距离进行分配店铺
        //note - 备注

        //空值校验
        //二：先保存寻主消息 - 自增长id
        //查询出当前登录人的登录信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //查询具体的登录人
        User user = userMapper.findByLogininfoId(logininfo.getId());
        //将这个具体的用户的userid存到寻主消息中
        searchMasterMsg.setUserId(user.getId());
        //再将这个寻主消息存到数据库里
        searchMasterMsgMapper.add(searchMasterMsg);
        //三：百度AI智能审核
        Boolean textAudit = baiduAiAuditService.textAudit(searchMasterMsg.getName()
                + searchMasterMsg.getTitle() + searchMasterMsg.getCoatColor());
        Boolean imageAudit = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        //3.1.审核成功
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(searchMasterMsg.getId());
        if (textAudit && imageAudit){
            //修改寻主消息表中的状态：0 - 1
            searchMasterMsg.setState(1);
            //修改审核表中的状态
            log.setState(1);
            log.setNote("发布成功");
            searchMasterMsgAuditLogMapper.add(log);
            //分配最近的店铺：分配失败：1.放入寻主池改状态1-3
            //先查询出所有的店铺
            List<Shop> shops = shopMapper.findAll();
            //获取寻主消息中的地址
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            //再进行距离的对比，获取到最近的店铺
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            //如果找到了就修改状态并发送短信，如果没找到就放到寻主池中
            if (nearestShop == null){
                searchMasterMsg.setState(3);
            }else{
                //给寻主消息设置一个店铺id
                searchMasterMsg.setShopId(nearestShop.getId());
                //给店铺管理员发送信息
                Employee admin = employeeMapper.findById(nearestShop.getAdminId());
                //SmsUtils.sendSms(admin.getPhone(),"你有新的订单请及时前往"+ searchMasterMsg.getAddress() +"接回宠物");
                System.out.println("你有新的订单请及时前往"+ searchMasterMsg.getAddress() +"接回宠物");
            }
            searchMasterMsgMapper.update(searchMasterMsg);
        }else{//审核失败
            //修改寻主消息表中的状态
            /*searchMasterMsg.setState(-1);
            searchMasterMsgMapper.update(searchMasterMsg);*/
            //修改审核表中的状态
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);

            searchMasterMsgMapper.delete(searchMasterMsg.getId());
            //发送审核失败信息
            //SmsUtils.sendSms(admin.getPhone(),"审核失败，请修改信息后重新提交审核");
            //System.out.println("审核失败，请修改信息后重新提交审核");
            return AjaxResult.me().setSuccess(false).setMessage("审核失败");
        }
        return new AjaxResult();
    }

    @Override
    @Transactional
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //获取登录人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //查询出user对象
        User user = userMapper.findByLogininfoId(logininfo.getId());
        //获取用户id
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        //获取登录人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //查询出employee对象
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        //获取用户id
        query.setShopId(employee.getShopId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> pool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        //获取登录人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //查询出employee对象
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        //获取用户id
        query.setShopId(employee.getShopId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        //获取登录人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //查询出employee对象
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        //获取用户id
        query.setShopId(employee.getShopId());
        return super.queryPage(query);
    }

    @Override
    @Transactional
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    @Transactional
    public void accept(Map<String, String> map) {
        Long msgId = Long.parseLong(map.get("msgId"));
        long empId = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        //一.校验当前订单是否已经在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.findByMsgId(msgId);
        //判断当前订单是否存在(订单正在处理)
        if (order != null){
            throw new BusinessException("订单正在处理，请勿重复接单");
        }

        //二.通过msgId生成一个pet对象,并且存入到系统中
        SearchMasterMsg msg = searchMasterMsgMapper.findById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.add(pet);

        //三.生成收购订单
        OrderPetAcquisition orderTemp = buildOrder(msg,empId,pet,note);
        orderPetAcquisitionMapper.add(orderTemp);

        //四.通过处理人去接回宠物
        //Employee employee = employeeMapper.findById(empId);
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请及时处理，地址："+msg.getAddress());
        System.out.println("请在两天内前往" + msg.getAddress() + "接回宠物");
    }

    private OrderPetAcquisition buildOrder(SearchMasterMsg msg, long empId, Pet pet, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //订单编号：根据用户id和年月日计算出来的
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(note);
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        order.setPrice(msg.getPrice());
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setShopId(msg.getShopId());
        //这里是领养人 - 宠物还没有被领养，所以没有
        //pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return  pet;
    }


}
